package middleware

import (
	"net/http"
	"strings"
	"software/config"

	"github.com/gin-gonic/gin"
)

// JWTAuthMiddleware 校验JWT并将user_id注入context
func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "未提供Token"})
			c.Abort()
			return
		}

		// 支持Bearer token格式
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
			c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "Token格式错误"})
			c.Abort()
			return
		}

		claims, err := config.ParseToken(parts[1])
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"success": false, "message": "Token无效或已过期"})
			c.Abort()
			return
		}

		// 注入user_id到context
		c.Set("user_id", claims.UserID)
		c.Next()
	}
} 